import React, { useState, useEffect } from 'react';
import { Card, Result, Space, Tag, Button, Divider, Collapse, message, Spin } from 'antd';
import { 
  TrophyOutlined, ClockCircleOutlined, CheckCircleOutlined, 
  CloseCircleOutlined, HomeOutlined, ReloadOutlined 
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { Submission, QuestionType } from '@/types/question';
import { questionService } from '@/services/questionService';
import CodeHighlight from '@/components/CodeBlock';
import styles from './ExamResult.module.css';

const { Panel } = Collapse;

const ExamResult: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(true);
  const [submission, setSubmission] = useState<Submission | null>(null);

  useEffect(() => {
    if (id) {
      loadResult();
    }
  }, [id]);

  const loadResult = async () => {
    if (!id) return;
    setLoading(true);
    try {
      const response = await questionService.getSubmission(Number(id));
      setSubmission(response.data.data);
    } catch (error) {
      message.error('加载成绩失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <Spin tip="加载中..." size="large" style={{ marginTop: '20%' }} />;
  }

  if (!submission) {
    return <Result status="error" title="未找到提交记录" />;
  }

  const isPassed = submission.total_score >= (submission.paper_detail?.passing_score || 60);

  return (
    <div className={styles.container}>
      {/* 成绩展示 */}
      <Card className={styles.resultCard}>
        <Result
          status={isPassed ? 'success' : 'warning'}
          icon={isPassed ? <TrophyOutlined /> : <CloseCircleOutlined />}
          title={isPassed ? '恭喜通过！' : '未通过考试'}
          subTitle={
            <Space direction="vertical" size="middle">
              <div style={{ fontSize: 48, fontWeight: 'bold', color: isPassed ? '#52c41a' : '#fa8c16' }}>
                {submission.total_score.toFixed(1)} 分
              </div>
              <Space size="large">
                <Tag color="blue" style={{ fontSize: 16, padding: '4px 12px' }}>
                  正确率：{(submission.score_ratio * 100).toFixed(1)}%
                </Tag>
                <Tag color="green" style={{ fontSize: 16, padding: '4px 12px' }}>
                  答对：{submission.correct_count}/{submission.total_count} 题
                </Tag>
                <Tag color="orange" style={{ fontSize: 16, padding: '4px 12px' }}>
                  用时：{Math.floor((new Date(submission.submit_time || '').getTime() - new Date(submission.start_time).getTime()) / 1000 / 60)}分钟
                </Tag>
              </Space>
            </Space>
          }
          extra={
            <Space>
              <Button 
                type="primary" 
                icon={<HomeOutlined />}
                onClick={() => navigate('/client/paper/list')}
              >
                返回试卷列表
              </Button>
              <Button 
                icon={<ReloadOutlined />}
                onClick={() => navigate(`/client/paper/${submission.paper}`)}
              >
                再做一次
              </Button>
            </Space>
          }
        />
      </Card>

      <Divider />

      {/* 答题详情 */}
      {submission.answer_records && submission.answer_records.length > 0 && (
        <Card title="答题详情" className={styles.detailCard}>
          <Collapse>
            {submission.answer_records.map((record, index) => (
              <Panel
                key={record.id}
                header={
                  <Space>
                    {record.is_correct ? (
                      <CheckCircleOutlined style={{ color: '#52c41a' }} />
                    ) : (
                      <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
                    )}
                    <span>第{index + 1}题</span>
                    <Tag color={record.is_correct ? 'success' : 'error'}>
                      {record.score.toFixed(1)}分
                    </Tag>
                    <span style={{ color: '#666' }}>
                      {record.question_detail?.title || record.question_detail?.type_display}
                    </span>
                  </Space>
                }
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <strong>您的答案：</strong>
                    <Tag color="blue">
                      {Array.isArray(record.user_answer) 
                        ? record.user_answer.join(', ')
                        : JSON.stringify(record.user_answer)}
                    </Tag>
                  </div>

                  {submission.paper_detail?.show_answer_after_submit && (
                    <div>
                      <strong>正确答案：</strong>
                      <Tag color="green">
                        {/* 这里需要从 question_detail 获取正确答案 */}
                      </Tag>
                    </div>
                  )}

                  {submission.paper_detail?.show_analysis_after_submit && record.question_detail?.answer_explanation && (
                    <div className={styles.explanation}>
                      <strong>解析：</strong>
                      <div>{record.question_detail.answer_explanation}</div>
                    </div>
                  )}
                </Space>
              </Panel>
            ))}
          </Collapse>
        </Card>
      )}
    </div>
  );
};

export default ExamResult;

